<template>
	<view class="certificate-detail" :class="themeName">
		<!-- #ifndef H5 -->
		<navbar :title="config.detail_data.detail_title"></navbar>
		<!-- #endif -->

		<view class="certificate-item p-30">
			<view class="head-title m-b-30">{{config.detail_data.detail_desc}}</view>
			<view class="certificate p-20">
				<view class="certificate-main">
					<view class="line">
						<view class="title">{{config.cert.code_field}}</view>
						<view class="desc">{{certInfo.sn}}</view>
					</view>
					<view class="line">
						<view class="title">{{config.cert.name_field}}</view>
						<view class="desc">{{certInfo.title}}</view>
					</view>
					<view class="line" v-if="config.certificate_type_show">
						<view class="title">{{config.cert.type_field}}</view>
						<view class="desc">{{certInfo.category_desc}}</view>
					</view>
					<view class="line" v-if="config.certificate_addtime_show">
						<view class="title">{{config.cert.addtime_field}}</view>
						<view class="desc">{{certInfo.create_time}}</view>
					</view>
					<view class="line" v-if="config.certificate_times_show">
						<view class="title">{{config.cert.times_field}}</view>
						<view class="desc">{{certInfo.query_count}}</view>
					</view>
					<view class="line" v-for="item,idx in certInfo.other_data" :key="idx">
						<view class="title">{{item.name}}</view>
						<view class="desc">{{item.value}}</view>
					</view>
				</view>
			</view>

			<u-gap height="180" v-if="config.original_query_enabled || config.original_download_enabled"></u-gap>

			<view class="functions" v-if="config.original_query_enabled || config.original_download_enabled">
				<view class="button-group">
					<view class="button-item" @tap="viewCert" v-if="config.original_query_enabled">
						{{config.detail_btns.view_btn}}
					</view>
					<block v-if="config.original_download_enabled">
						<!-- #ifdef MP-WEIXIN -->
						<view class="button-item" @tap="downloadFile">{{config.detail_btns.original_download}}</view>
						<!-- #endif -->
						<!-- #ifdef H5 -->
						<view class="save_path m-t-10" @tap="saveH5File(certInfo.original_files[0])"
							v-if="originalFilesLength ==1">{{config.detail_btns.original_download}}</view>
						<view class="button-item" @tap="downloadFile" v-else>{{config.detail_btns.original_download}}
						</view>
						<!-- #endif -->
					</block>
				</view>
			</view>
		</view>

		<u-popup v-model="shareDownloadVisible" mode="center" width="90%">
			<view class="down-box">
				<block v-for="item,idx in certInfo.original_files" :key="idx">
					<view class="file-box flex u-border-bottom p-b-20 col--center row-between">
						<view class="name m-b-10">{{config.detail_data.file_desc}}：{{item.name}}</view>
						<!-- #ifdef MP-WEIXIN -->
						<u-loading mode="circle" v-if="loading"></u-loading>
						<view class="save_path m-t-10" v-else @tap="downloadCert(item)">
							{{config.detail_btns.download_desc}}
						</view>
						<!-- #endif -->
						<!-- #ifdef H5 -->
						<view class="save_path m-t-10" @tap="saveH5File(item)">{{config.detail_btns.download_desc}}
						</view>
						<!-- #endif -->
					</view>
				</block>
			</view>
			<view class="share-btns flex row-between m-t-20">
				<view class="share" @tap="closeDownPop">{{config.detail_btns.close_desc}}</view>
			</view>
		</u-popup>

		<u-popup v-model="previewVisible" mode="center" :zIndex="100" width="90%">
			<view class="down-box">
				<goods-swiper :images="previewImage" imagesWidth="100%" imagesHeight="100%" />
			</view>
			<view class="share-btns flex row-between m-t-20">
				<view class="share" @tap="closeDownPop">{{config.detail_btns.close_desc}}</view>
			</view>
		</u-popup>

	</view>
</template>


<script>
	import {
		apiCertificateConfig,
		apiCertificateDetail
	} from '@/api/certificate'
	import {
		strToParams
	} from "@/utils/tools.js";
	export default {
		name: 'CertificateDetail',
		data() {
			return {
				certInfo: {},
				cert_id: '',
				config: {
					cert: {
						code_field: '证书编号',
						name_field: '证书名称',
						type_field: '证书类型',
						addtime_field: '创建时间',
						times_field: '查询次数',
					},
					detail_data: {
						detail_title: '证书详情',
						detail_desc: '证书信息',
						file_desc: '文件',
						fail_save: '保存失败',
						fail_download: '失败请重新下载',
						auth_title: '您已拒绝访问相册权限',
						auth_desc: '证书将以图片方式下载到您的相册，请同意授权',
						save_title: '文件已保存到手机相册',
						save_desc: "位于tencent/MicroMsg/WeiXin下 \r\n将保存的文件重命名改为[ .{ext} ]后缀即可",
						no_cert_original: '暂无证书原件'
					},
					detail_btns: {
						view_btn: '证书查看',
						original_download: '证书原件下载',
						close_desc: '关闭',
						download_desc: '下载',
						auth_btn: '去授权',
						save_btn: '确定',
					},
					certificate_type_show: 1,
					certificate_addtime_show: 1,
					certificate_times_show: 1,
					original_download_enabled: 0,
					original_query_enabled: 0
				},
				shareDownloadVisible: false,
				loading: false,
				downloadInfo: {},
				previewVisible: false,
				previewImage: []
			}
		},

		computed: {
			originalFilesLength() {
				return this.certInfo.original_files?.length
			}
		},

		methods: {
			getConfig() {
				return apiCertificateConfig().then((data) => {
					this.config = this.$zhTran(data)
					for (var i in data) {
						if (Object.keys(data[i]).length > 0) this.config[i] = data[i]
					}

					// #ifdef H5
					uni.setNavigationBarTitle({
						title: this.config.detail_data.detail_title,
					});
					// #endif

					return Promise.resolve(data);
				}).catch(err => {
					return Promise.reject(err);
				});
			},
			getDetail() {
				return apiCertificateDetail({
					cert_id: this.cert_id
				}).then((data) => {
					this.certInfo = this.$zhTran(data)
					return Promise.resolve(data);
				}).catch(err => {
					return Promise.reject(err);
				});
			},
			viewCert() {
				// 阻止重复操作

				var images = [],
					original_files = this.certInfo.original_files

				if (Object.keys(original_files).length == 0) {
					console.log('123')
					this.$toast({
						title: this.config.detail_data.no_cert_original
					})
					return
				}

				for (var i in original_files) {
					if (original_files[i].image.length > 0) {
						images = images.concat(original_files[i].image); //追加新数据
					} else {
						images.push(original_files[i].original)
					}
				}
				// #ifdef MP-WEIXIN
				uni.previewImage({
					urls: images
				});
				// #endif

				// #ifdef H5
				this.previewImage = images
				this.previewVisible = true
				// #endif
			},
			downloadFile() {

				if (Object.keys(this.certInfo.original_files).length == 0) {
					this.$toast({
						title: this.config.detail_data.no_cert_original
					})
					return
				}

				// #ifdef MP-WEIXIN
				if (this.originalFilesLength == 1) {
					this.downloadCert(this.certInfo.original_files[0])
				} else {
					this.shareDownloadVisible = true
				}
				// #endif
				// #ifdef H5
				this.shareDownloadVisible = true
				// #endif
			},
			async downloadCert(row) {

				if (this.loading) return

				var checkAuth = await this.checkSetting()
				console.log('checkAuth', checkAuth)
				if (!checkAuth) {
					this.downloadInfo = row
					this.getAuthorize()
					return
				}

				this.loading = true

				var that = this
				const fs = uni.getFileSystemManager()
				var downloadTask = uni.downloadFile({
					url: row.original,
					success(res) {
						console.log('res', res)
						if (res.statusCode === 200) {
							var savePath = wx.env.USER_DATA_PATH + "/" + row.name + ".jpg"
							fs.saveFile({
								tempFilePath: res.tempFilePath,
								filePath: savePath,
								success(res2) {
									uni.saveImageToPhotosAlbum({
										filePath: savePath,
										success: (res3) => {
											var save_desc = that.config.detail_data
												.save_desc
											uni.showModal({
												title: that.config.detail_data
													.save_title,
												content: save_desc.replace('{ext}',
													row.ext),
												confirmColor: that.themeColor,
												confirmText: that.config
													.detail_btns
													.save_btn,
												showCancel: false
											})
										},
										fail: (err) => {
											that.$toast({
												title: that.config.detail_data
													.fail_save,
											});
										},
									});
								},
								complete() {
									that.loading = false
								}
							})
						}
					},
					fail(res) {
						that.loading = false
						that.$toast({
							title: that.config.detail_data.fail_download
						})
						console.log('fail', res)
					}
				})
			},
			closeDownPop() {
				this.shareDownloadVisible = false
				this.previewVisible = false
			},
			async checkSetting() {
				var that = this
				const [error, data] = await uni.getSetting()
				if (data.authSetting['scope.writePhotosAlbum'] == undefined || !data.authSetting[
						'scope.writePhotosAlbum']) {
					return false
				}
				return true
			},
			async getAuthorize() {
				var that = this
				const [error, data] = await uni.showModal({
					title: that.config.detail_data.auth_title,
					content: that.config.detail_data.auth_desc,
					confirmText: that.config.detail_btns.auth_btn
				})

				if (data.confirm) {
					uni.authorize({
						scope: 'scope.writePhotosAlbum',
						success() {
							// 用户已经同意小程序使用功能，后续调用接口不会弹窗询问
							that.downloadCert(that.downloadInfo)
						}
					})
					// await uni.openSetting()
				}
			},
			saveH5File(row) {

				if (Object.keys(this.certInfo.original_files).length == 0) {
					this.$toast({
						title: this.config.detail_data.no_cert_original
					})
					return
				}

				let link = document.createElement("a");
				link.href = row.original;
				link.style.display = "none"; //a标签隐藏
				link.download = row.name;
				document.body.appendChild(link);
				link.click();
				document.body.removeChild(link)
			}
		},

		async onLoad() {
			const options = this.$Route.query
			const scene = options["scene"]; // 微信二维码
			this.cert_id = options.cert_id
			if (this.$Route.meta.atitle) {
				uni.setNavigationBarTitle({
					title: this.$zhTran(this.$Route.meta.atitle)
				})
			}

			if (scene) {
				this.cert_id = strToParams(decodeURIComponent(scene))["id"]
			}

			await this.getConfig()
			await this.getDetail()
			setTimeout(() => {}, 0.5 * 1000)
		},
		onUnload() {},
	}
</script>


<style lang="scss">
	page {
		height: 100%;
		padding: 0;
	}

	.certificate-detail {
		height: 100%;
		display: flex;
		flex-direction: column;

		.certificate-item {
			flex: 1;
			min-height: 0;
		}

		.head-title {
			font-size: 28rpx;
			color: rgba(128, 128, 128, 1);
		}
	}

	.certificate {
		border-radius: 10px;
		background-color: #FFFFFF;

		&-main {

			.line {

				margin-top: 20rpx;
				padding-bottom: 20rpx;
				border-bottom: 1rpx solid rgba(241, 241, 241, 1);

				.title {
					font-size: 24rpx;
					color: rgba(128, 128, 128, 1);
				}

				.desc {
					font-size: 28rpx;
					color: rgba(0, 0, 0, 1);
					margin-top: 20rpx;
				}
			}
		}
	}

	.functions {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		display: flex;
		align-items: center;
		height: calc(100rpx + constant(safe-area-inset-bottom));
		height: calc(100rpx + env(safe-area-inset-bottom));
		padding: 0 24rpx constant(safe-area-inset-bottom) 24rpx;
		padding: 0 24rpx env(safe-area-inset-bottom) 24rpx;

		.button-group {
			flex: 1;
			display: flex;
			justify-content: space-between;

			.button-item {
				flex: 1;
				box-sizing: border-box;
				display: flex;
				justify-content: center;
				align-items: center;
				margin-left: 20rpx;
				height: 74rpx;
				font-size: 28rpx;
				border-radius: 6rpx;
				color: #fff;
				background: linear-gradient(90deg, rgba(93, 136, 252, 1) 0%, rgba(56, 103, 255, 1) 100%);
				box-shadow: 0px 0px 10px 0px rgba(57, 104, 255, 0.34);

				&--disabled::before {
					position: absolute;
					top: 0;
					bottom: 0;
					left: 0;
					right: 0;
					height: 100%;
					display: block;
					content: "";
					background: rgba(255, 255, 255, .3) !important;
				}
			}

			.button-item:first-child {
				margin-left: 0;
			}
		}
	}

	.down-box {
		padding: 30rpx;
		background-color: #fff;
		border-radius: 10rpx;

		.file-box {
			margin-bottom: 20rpx;

			.save_path {
				color: rgba(56, 103, 255, 1);
			}
		}
	}

	.share-btns {
		&>view {
			width: 100%;
			font-size: 26rpx;
			color: #fff;
			border-radius: 10rpx;
			padding: 20rpx 0;
			text-align: center;
			background: linear-gradient(90deg, rgba(93, 136, 252, 1) 0%, rgba(56, 103, 255, 1) 100%);
			box-shadow: 0px 0px 10px 0px rgba(57, 104, 255, 0.34);
		}
	}
</style>